<template>
  <div class="app-container">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="45%"
      v-dialogDrag
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        v-loading="formLoading"
        label-width="100px"
      >
        <el-form-item label="存储广告图片地址" prop="imageUrl">
          <el-input
            v-model="formData.imageUrl"
            placeholder="请输入存储广告图片地址"
            @input="onImageUrlChange"
          />
          <div v-if="formData.imageUrl" class="image-preview">
            <img :src="formData.imageUrl" alt="图片预览" class="preview-image" />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">
          确 定
        </el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as AdpictureApi from "@/api/system/adpicture";

export default {
  name: "AdpictureForm",
  data() {
    return {
      dialogTitle: "",
      dialogVisible: false,
      formLoading: false,
      formData: {
        id: undefined,
        imageUrl: undefined,
      },
      formRules: {
        imageUrl: [
          { required: true, message: "存储广告图片地址不能为空", trigger: "blur" },
          { max: 255, message: "长度不能超过255个字符", trigger: "blur" }
        ]
      },
    };
  },
  methods: {
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      if (id) {
        this.formLoading = true;
        try {
          const res = await AdpictureApi.getAdpicture(id);
          this.formData = res.data;
          this.dialogTitle = "修改存储广告图片信息";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增存储广告图片信息";
      }
    },

    async submitForm() {
      try {
        await this.$refs.formRef.validate();
        this.formLoading = true;
        const data = this.formData;
        if (data.id) {
          // 调用修改接口
          await AdpictureApi.updateAdpicture(data);
          this.$modal.msgSuccess("修改成功");
        } else {
          // 调用新增接口
          await AdpictureApi.createAdpicture(data);
          this.$modal.msgSuccess("新增成功");
        }
        this.dialogVisible = false;
        this.$emit("success");
      } catch (error) {
        console.error("提交失败", error);
        this.$modal.msgError("提交失败，请检查网络或联系管理员");
      } finally {
        this.formLoading = false;
      }
    },

    reset() {
      this.formData = {
        id: undefined,
        imageUrl: undefined,
      };
      this.$nextTick(() => {
        this.$refs.formRef?.resetFields();
      });
    },

    onImageUrlChange() {
      if (this.formData.imageUrl) {
        const isValidUrl = /^(https?:\/\/).+\.(jpg|png|gif|webp)$/i.test(this.formData.imageUrl);
        if (!isValidUrl) {
          this.$message.error("请输入有效的图片URL（支持jpg/png/gif/webp）");
          this.formData.imageUrl = ""; // 清空无效的图片地址
        }
      }
    }
  },
};
</script>

<style scoped>
.image-preview {
  margin-top: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-image {
  max-width: 100%;
  max-height: 200px;
  border: 1px solid #ccc;
  border-radius: 4px;
}
</style>